/*
 * Copyright (c) 2009 Piotr Piastucki
 *
 * This file is part of Patchca CAPTCHA library.
 *
 * Patchca is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Patchca is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Patchca. If not, see <http://www.gnu.org/licenses/>.
 */
package org.patchca.utils.encoder;

import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.patchca.service.Captcha;
import org.patchca.service.CaptchaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EncoderHelper {
	private final static Logger log = LoggerFactory.getLogger(EncoderHelper.class);

	/**
	 * 生成图像，并返回答案
	 *
	 * @param service
	 * @param format
	 * @param os
	 * @return
	 * @throws IOException
	 */
	public static String getChallangeAndWriteImage(CaptchaService service, String format, OutputStream os) throws IOException {
		Captcha captcha = service.getCaptcha();
		ImageIO.write(captcha.getImage(), format, os);
		return captcha.getChallenge();
	}

	/**
	 * 生成图像，返回图像封装对象
	 *
	 * @param service
	 * @param format
	 * @param os
	 * @return
	 * @throws IOException
	 */
	public static Captcha getCaptchaAndWriteImage(CaptchaService service, String format, OutputStream os) throws IOException {
		Captcha captcha = service.getCaptcha();
		long start = System.currentTimeMillis();
		ImageIO.write(captcha.getImage(), format, os);
		if (log.isDebugEnabled()) {
			log.debug("ImageIO.write consuming_time [{}] ms.", System.currentTimeMillis() - start);
		}
		return captcha;
	}

}
